package com.yundasys.springbootxa.config;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import javax.transaction.UserTransaction;
import javax.xml.crypto.Data;
import java.io.IOException;

/**
 * @PACKAGE_NAME: com.yundasys.springbootxa.config
 * @NAME: ConfigDb131
 * @USER: jiangta
 * @DATE: 2021/1/11
 * @TIME: 9:20 下午
 * @PROJECT_NAME: springboot-labs
 */
@Configuration
@MapperScan(value = "com.yundasys.springbootxa.xa131.dao",sqlSessionFactoryRef = "sqlSessionFactoryBean131")
public class ConfigDb131 {

    @Bean(name = "db131")
    public DataSource db131() {
        MysqlXADataSource dataSource = new MysqlXADataSource();
        dataSource.setUser("ggs");
        dataSource.setPassword("wEK8lQ91gYnkzIG9");
        dataSource.setUrl("jdbc:mysql://10.19.186.215:3306/sharding_order?characterEncoding=UTF-8&useSSL=false");

        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(dataSource);
        return dataSource;
    }

    @Bean(name="sqlSessionFactoryBean131")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("db131")DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("mapper/db131/*.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean("xaTransaction")
    public JtaTransactionManager jtaTransactionManager() {
        UserTransaction userTransaction = new UserTransactionImp();
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        return new JtaTransactionManager(userTransaction,userTransactionManager);
    }
}
